<?php

namespace app\crm\model;


use think\Db;
use app\admin\model\Common;
use think\Request;
use think\Validate;

class Invoice extends Common
{
    protected $name = 'crm_invoice';
    protected $createTime = 'created_time';
    protected $updateTime = '';
    protected $autoWriteTimestamp = true;
    private $check_status=[0=>"待审",1=>"审批中",2=>"通过",3=>"失败",4=>"撤销"];
    /**
     * [getDataList 报销list]
     * @author Michael_xu
     * @param     [string]                   $map [查询条件]
     * @param     [number]                   $page     [当前页数]
     * @param     [number]                   $limit    [每页数量]
     * @return    [array]                    [description]
     */
    /**
     * [getDataList 财务list]
     * @author Michael_xu
     * @param     [string]                   $map [查询条件]
     * @param     [number]                   $page     [当前页数]
     * @param     [number]                   $limit    [每页数量]
     * @return    [array]                    [description]
     */
    public function getDataList($request)
    {
        unset($request["search"]);
        $request = $this->fmtRequest( $request );
        $map = $request['map'] ? : [];
        $user_id=$map["user_id"];
        unset($map["user_id"]);
        if(isset($map["customer_name"])){//客户名称
            $map["customer.name"]=["like","%".$map["customer_name"]["value"]."%"];
            unset($map["customer_name"]);
        }
        if(isset($map["invoice_unit"])){//开票单位名称
            $map["e.invoice_unit"]=["like","%".$map["invoice_unit"]["value"]."%"];
            unset($map["invoice_unit"]);
        }
        if(isset($map['invoice_type'])) {
            $map["e.invoice_type"]=trim($map["invoice_type"]["value"]);
            unset($map["invoice_type"]);
        }
        if(isset($map['order_type'])) {
            $map["e.order_type"]=trim($map["order_type"]["value"]);
            unset($map["order_type"]);
        }
        if(isset($map["order_sn_all"])){//财务编号
            $map["e.order_sn_all"]=["like","%".$map["order_sn_all"]["value"]."%"];
            unset($map["order_sn_all"]);
        }
        if(isset($map["department"])){//所属部门
            $map["e.department"]=["like","%".$map["department"]["value"]."%"];
            unset($map["department"]);
        }
        if(isset($map["user_name"])){//开票发起人
            $map["admin.realname"]=["like","%".$map["user_name"]["value"]."%"];
            unset($map["user_name"]);
        }
        if(isset($map["updated_time"])){//开票时间查询
            $map["e.updated_time"]=array(array('egt',date("Y-m-d H:i:s",$map["updated_time"]["start"])),array('elt',date("Y-m-d H:i:s",$map["updated_time"]["end"])),'and');;
            unset($map["updated_time"]);
        }
        if(isset($map["status"])){//审核状态
            $check_status=["待审核"=>"0","通过"=>"2","审核中"=>"1","撤销"=>"4","失败"=>"3"];
            $map["e.status"]=$check_status[$map["status"]["value"]];
            unset($map["status"]);
        }
        //财务和超级管理员可以看所有，其他只能看对应自己和下级的  customer_name
        $isFinance=db("admin_access")->where(["user_id"=>$user_id,"group_id"=>9])->find();//是否是财务
        $isButler = db('admin_access')->where(["user_id"=>$user_id,"group_id"=>32])->find();//管家
        if(!$isButler && !$isFinance && $user_id!=1){
            $childIds=$this->getChildIds($user_id);
            $childIds[]=$user_id;
            $map["e.user_id"]=["in",$childIds];
        }
        $list = db('crm_invoice')->alias('e')
            ->join('admin_user admin',"admin.id=e.user_id","left")
            ->join('__CRM_CUSTOMER__ customer',"customer.customer_id=e.customer_id","left")
            ->where($map)
            ->limit(($request['page']-1)*$request['limit'], $request['limit'])
            ->field('e.*,customer.name customer_name,admin.realname user_name')
            ->order("e.id desc")
            ->select();
        if($list){
            foreach ($list as $k=>$v){
                $list[$k]["status"]=$this->check_status[$v["status"]];
            }
        }
        $dataCount =  db('crm_invoice')->alias('e')
            ->join('admin_user admin',"admin.id=e.user_id","left")
            ->join('__CRM_CUSTOMER__ customer',"customer.customer_id=e.customer_id","left")
            ->where($map)
            ->count();
        $data = [];
        $data['list'] = $list;
        $data['dataCount'] = $dataCount ? : 0;
        return $data;
    }

    /**
     * @param $user_id 用户id
     * 获取客户列表(仅限审核通过)
     */
    public function get_customer($user_id,$name="",$order_type="正常开票"){
        //财务和超级管理员可以看所有，其他只能看对应自己和下级的  customer_name
        $isFinance=db("admin_access")->where(["user_id"=>$user_id,"group_id"=>9])->find();//是否是财务
        $isButler = db('admin_access')->where(["user_id"=>$user_id,"group_id"=>32])->find();//管家
        if(!$isButler && !$isFinance && $user_id!=1){
            $childIds=$this->getChildIds($user_id);
            $childIds[]=$user_id;
            $where["owner_user_id"]=["in",$childIds];
        }
        if($name) $where["name"]=array("like","%{$name}%");
        // 查询是否为咨询会计
        $iszxkj = db('admin_access')->where(["user_id"=>$user_id,"group_id"=>36])->find();//咨询会计
        if($iszxkj && !$isButler && !$isFinance && $user_id!=1) {
            $whereOr = ' consult_user_id = '.$user_id;
            if(isset($where["owner_user_id"])) {
                $whereOr .= ' or owner_user_id in('.implode(',',$where["owner_user_id"][1]).') ';
                unset($where["owner_user_id"]);
            }
            $data = Db::name('crm_customer')->where($where)->where($whereOr)->limit(20)->select();
        } else {
            $data=DB::name("crm_customer")->where($where)->field("customer_id,name")->limit(20)->select();
        }
        
        if($data){
            foreach ($data as $k=>$v){
                $contract=Db::name("crm_contract")->where(["customer_id"=>$v["customer_id"],"crm_upqdbn"=>$order_type])->field("contract_id,num")->select();
                if(!$contract){
                    unset($data[$k]);continue;
                }
                $data[$k]["contract"]=$contract;
            }
        }
        return array_values($data);
    }

    /**
     * @param $contract_id 合同id
     * 获取可报销的金额
     */
    public function get_invoice_money($contract_id,$department){
        $contractData=DB::name("crm_contract")->where(["contract_id"=>$contract_id,"crm_kfhgfp"=>$department])->field("crm_upqdbn,money")->find();
        if(!$contractData) return "";
        if($contractData["crm_upqdbn"]=="正常开票"){
            $data=DB::name("crm_finance")->where(["check_status"=>2,"order_type"=>"回款","contract_id"=>$contract_id,"department"=>$department])
                ->field("order_sn,money total_money")->select();//回款编号、总金额
            if($data){
                foreach ($data as $k=>$v){
                    // 退款金额
                    $refund_money = db("crm_finance")->where(["receivables_code"=>$v["order_sn"],"order_type"=>"退款","check_status"=>["in",[0,1,2]]])->sum("refund_money");
                    $data[$k]["used_money"]=DB::name("crm_invoice_detail")->where(["order_sn"=>$v["order_sn"],"status"=>array("in",["0","1","2"])])->sum("money");//已经开票金额
                    $data[$k]["type"]=$contractData["crm_upqdbn"];
                    $money = bcsub($v["total_money"],$data[$k]["used_money"],2);//可开票金额
                    $data[$k]["money"]=bcsub($money,$refund_money,2);//可开票金额
                    $data[$k]["total_money"]=bcsub($data[$k]["total_money"],$refund_money,2);//可开票金额
                }
            }
        }else{
            $used_money=DB::name("crm_invoice_detail")->alias("d")
                ->join("crm_invoice i","i.id=d.invoice_id")
                ->where(["d.contract_id"=>$contract_id,"d.status"=>array("in",["0","1","2"]),"i.department"=>$department])
                ->sum("d.money");//已经开票金额
            $data=[[
                "order_sn"=>"",//回款编号
                "type"=>$contractData["crm_upqdbn"],//先票后款获取合同金额、正常开票获取汇款金额
                "total_money"=>$contractData["money"],//总金额
                "used_money"=>$used_money,//已开票金额
                "money"=>bcsub($contractData["money"],$used_money,2),//可开票金额
            ]];
        }
        return $data;
    }
    /**
     * @param $user_id
     * 获取用户的所有下级
     */
    public function getChildIds($user_id){
        $childsArr=db("admin_user")->where(["parent_id"=>$user_id])->column("id");
        if($childsArr){
            foreach ($childsArr as $v){
                $arr=$this->getChildIds($v);
                if($arr) $childsArr=array_merge($childsArr,$arr);
            }
        }
        return $childsArr;
    }

}